package com.xch.dao.impl;

import com.xch.dao.BaseAdminDao;
import com.xch.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class AdminDaoMysql implements BaseAdminDao {
    private static final String SQL_UPDATE_LOGIN_TIME = "UPDATE EADMIN SET LOGINTIME=?,LOGINIP=? WHERE USERNAME=?";
    private static final String SQL_LOGIN = "SELECT ID FROM EADMIN WHERE USERNAME=? AND PASSWORD=?";

    /**
     * 根据用户名更新时间和登录ip
     *
     * @param username
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        //1. 获取链接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;

        //2. 预编译语句
        try {
            state = conn.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            //3. 填充参数
            state.setDate(1,new java.sql.Date(date.getTime()));
            state.setString(2,ip);
            state.setString(3,username);
            //4. 执行语句
            state.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //5. 释放资源
            DruidUtil.close(conn,state,null);
        }

    }

    /**
     * 管理员账号密码登录
     *
     * @param username
     * @param password
     * @return 登录的结果 true 登录成功 false 登录失败
     */
    @Override
    public boolean login(String username, String password) {
        //1. 获取链接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet resultSet =null;

        //2. 预编译语句
        try {
            state = conn.prepareStatement(SQL_LOGIN);
            //3. 填充参数
            state.setString(1,username);
            state.setString(2,password);
            //4. 执行语句
            resultSet = state.executeQuery();
            //5. 根据查询结果返回true和false
            return resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //5. 释放资源
            DruidUtil.close(conn,state,resultSet);
        }
        return false;
    }
}
